﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using EBA.Localization;


namespace EBA.Data
{
    /// <summary>
    /// 将<see cref="ObjectSet{T}"/>实例包装为<see cref="IRepository{T}"/>对象。
    /// </summary>
    public class EntityRepository<Entity, IEntity> :EntityQuery<Entity,IEntity>, IRepository<IEntity> where Entity : class,IEntity, new()
    {
        /// <summary>
        /// 构造函数。
        /// </summary>
        public EntityRepository(ObjectSet<Entity> table, params string[] includes)
            : base(table, null,includes)
        {
        }

        public EntityRepository(ObjectSet<Entity> table, Expression<Func<ITransientRepository<IEntity>>> createTransient, params string[] includes)
            : base(table, null, includes)
        {
            this._CreateTransient = createTransient;
        }

        /// <summary>
        /// 新增指定实例。
        /// </summary>
        public virtual void Add(IEntity entity)
        {
            this.Table.AddObject((Entity)entity);
        }

        /// <summary>
        /// 删除指定实例。
        /// </summary>
        public void Delete(IEntity entity)
        {
            this.Table.DeleteObject((Entity)entity);
        }

        /// <summary>
        /// 批量删除匹配的实例。
        /// </summary>
        public virtual int DeleteAll(Expression<Func<IEntity, bool>> filter)
        {
            Expression<Func<Entity, bool>> predicate = Expression.Lambda<Func<Entity, bool>>(filter.Body,filter.Parameters);
            return this.Table.DeleteAll(predicate);
        }

        /// <summary>
        /// 批量删除指定的实例。
        /// </summary>
        /// <param name="entities"></param>
        public virtual void DeleteAll(IEnumerable<IEntity> entities)
        {
            foreach (var entity in entities)
            {
                this.Table.DeleteObject((Entity)entity);
            }
        }

        /// <summary>
        /// 创建一个实例。
        /// </summary>
        public virtual IEntity NewEntity()
        {
            return new Entity();
        }

        /// <summary>
        /// 批量更新匹配的对象。
        /// </summary>
        public virtual int UpdateAll(System.Linq.Expressions.Expression<Func<IEntity, bool>> filter, System.Linq.Expressions.Expression<Func<IEntity, object>> evaluator)
        {
            throw new NotImplementedException();
        }



        Expression<Func<ITransientRepository<IEntity>>> _CreateTransient;
        public ITransientRepository<IEntity> CreateTransient()
        {
            if (this._CreateTransient == null)
            {
                throw new NotSupportedException("This repository does not support to create a transient copy.".T());
            }
            else
            {
                return this._CreateTransient.Compile()();
            }
        }
    }
}

